
const matchList = document.getElementById('match-list');
console.log(matchList);
// 获取比赛列表的函数
async function fetchMatches() {
    try {
        const token = sessionStorage.getItem("token"); // 从 sessionStorage 获取 token
        console.log(token);
        const response = await fetch('http://localhost:8081/api/match', {
            method: 'GET',
            headers: {
                'Authorization': token, // 将 token 添加到请求头中
                'Content-Type': 'application/json' // 可选，设置请求体的类型
            }
        });

        if (!response.ok) {
            throw new Error('网络错误：无法获取比赛列表');
        }

        const matches = await response.json();
        renderMatchList(matches);
    } catch (error) {
        console.error(error);
        alert('获取比赛列表失败，可能是您没登录');
        location.href = "/login.html"
    }
}

// script.js

function renderMatchList(matches) {
    const matchList = document.getElementById('matchList');
    matchList.innerHTML = ''; // 清空之前的内容

    matches.forEach(match => {
        const matchItem = document.createElement('div');
        matchItem.className = 'match-item';

        const matchTeams = document.createElement('div');
        matchTeams.className = 'match-teams';
        matchTeams.innerText = `${match.teamA} vs ${match.teamB}`;

        const matchDetails = document.createElement('div');
        matchDetails.className = 'match-details';
        matchDetails.innerText = `Match ID: ${match.id}`;

        const matchButton = document.createElement('button');
        matchButton.className = 'match-button';
        matchButton.innerText = '去竞猜';
        matchButton.onclick = () => selectMatch(match, match.id);

        // 依次将内容添加到 matchItem
        matchItem.appendChild(matchTeams);
        matchItem.appendChild(matchDetails);
        matchItem.appendChild(matchButton);

        // 将每个比赛项添加到 matchList
        matchList.appendChild(matchItem);
    });
}





// 选择比赛
function selectMatch(match, matchId) {
    location.href = `match-detail.html?matchId=${matchId}&teamAid=${match.teamAId}&teamBid=${match.teamBId}`;
    return false;
}

// 页面加载时获取比赛列表
window.onload = fetchMatches;
